var admin_app = {
    /**
     * 统一处理响应
     * @param {Object} response - 服务器响应
     * @returns {Object} 处理后的数据
     * @throws {Error} 当响应不成功时抛出错误
     */
    handleResponse: function(response) {
        if (response.code === 1) {
            return response.data;
        }
        throw new Error(response.msg || 'Request failed');
    },

    /**
     * Check API key validity
     * @param {string} val - API key to validate
     * @param {Function} onSuccess - Success callback
     * @param {Function} onError - Error callback, receives full response object when code != 1
     */
    checkApiKey: function(val, onSuccess, onError) {
        // fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            { 
                action: 'auth_validate_key',
                api_key: val 
            },
            function(response) {
                fc5_utils.hideLoading();
                if (response.code === 1) {
                    const supportLanguageNum = response.data?.subscribe_info?.support_language_num || 1;
                    onSuccess && onSuccess(true, supportLanguageNum);
                } else {
                    console.error('Failed to validate key:', response.msg);
                    onError && onError(response);
                }
            },
            function(error) {
                // fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * Synchronously validate API key
     * @param {string} val - API key to validate
     * @returns {boolean} Validation result
     */
    validateApiKeySync: function(val) {
        try {
            const response = fc5_utils.postSync(
                falcon5_ajax_config.ajax_url,
                { 
                    action: 'auth_validate_key',
                    api_key: val 
                }
            );
            return admin_app.handleResponse(response) !== null;
        } catch (error) {
            console.error('API key validation failed:', error);
            return false;
        }
    },

    /**
     * Get cache directory
     * @param {Function} onSuccess - Success callback
     * @param {Function} onError - Error callback
     */
    getCacheDirectory: function(onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            { action: 'settings_get_cache_directory' },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('Failed to get cache directory:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * Get plugin settings
     * @param {Function} onSuccess - Success callback
     * @param {Function} onError - Error callback
     */
    getSettings: function(onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            { action: 'settings_get_settings' },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('Failed to get settings:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * Save plugin settings
     * @param {Object} settings - Settings to save
     * @param {Function} onSuccess - Success callback
     * @param {Function} onError - Error callback
     */
    saveSettings: function(settings, onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            { 
                action: 'settings_save_settings',
                settings: JSON.stringify(settings)
            },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('Failed to save settings:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * get cache list data
     * @param {Object} params - query params
     * @param {Function} onSuccess - success callback
     * @param {Function} onError - error callback
     */
    getCacheList: function(params, onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            {
                action: 'site_cache_list',
                page: params.page || 1,
                page_size: params.page_size || 10,
                keyword: params.keyword || '',
                language: params.language || ''
            },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('Failed to get cache list:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * fetch translation list
     * @param {Object} params - query params
     * @param {Function} onSuccess - success callback
     * @param {Function} onError - error callback
     */
    getTranslationList: function(params, onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            {
                action: 'entry_entry_list',
                page_id: params.page_id,
                original_lang: params.original_lang,
                translated_lang: params.translated_lang,
                keyword: params.keyword || '',
                page: params.page || 1,
                page_size: params.page_size || 10
            },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('Failed to get translation list:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * Check domain validity
     * @param {string} subDomain - Domain to validate
     * @param {string} langCode - Language code
     * @param {Function} onSuccess - Success callback
     * @param {Function} onError - Error callback
     */
    checkDomain: function(subDomain, langCode, onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            { 
                action: 'settings_validate_domain',
                sub_domain: subDomain,
                lang_code: langCode
            },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data.isValid);
                } catch (error) {
                    console.error('Failed to validate domain:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * Lock a page
     * @param {Object} params - Parameters
     * @param {number} params.cacheId - Cache ID
     * @param {number} params.pageId - Page ID
     * @param {Function} onSuccess - Success callback
     * @param {Function} onError - Error callback
     */
    lockPage: function(params, onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            {
                action: 'site_lock_page',
                cache_id: parseInt(params.cacheId, 10),
                page_id: parseInt(params.pageId, 10)
            },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('Failed to lock page:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * Unlock a page
     * @param {Object} params - Parameters
     * @param {number} params.cacheId - Cache ID
     * @param {number} params.pageId - Page ID
     * @param {Function} onSuccess - Success callback
     * @param {Function} onError - Error callback
     */
    unlockPage: function(params, onSuccess, onError) {
        fc5_utils.showLoading();
        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            {
                action: 'site_unlock_page',
                cache_id: parseInt(params.cacheId, 10),
                page_id: parseInt(params.pageId, 10)
            },
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('Failed to unlock page:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('Request failed:', error);
                onError && onError(error);
            }
        );
    },

    /**
     * 获取站点信息（使用 REST API）
     * @param {Object} params - 请求参数
     * @param {Function} onSuccess - 成功回调
     * @param {Function} onError - 错误回调
     */
    getSiteInfo: function(params, onSuccess, onError) {
        fc5_utils.showLoading();
        
        // 构建 REST API URL
        const restUrl = falcon5_ajax_config.rest_url + 'falcon5/v1/callback/site_info';
        
        fc5_utils.post(
            restUrl,
            params,
            function(response) {
                fc5_utils.hideLoading();
                try {
                    const data = admin_app.handleResponse(response);
                    onSuccess && onSuccess(data);
                } catch (error) {
                    console.error('获取站点信息失败:', error.message);
                    onError && onError(error.message);
                }
            },
            function(error) {
                fc5_utils.hideLoading();
                console.error('请求失败:', error);
                onError && onError(error);
            }
        );
    }
};